
   <!DOCTYPE html>
   <html>
       <head>
           <title>富文本编辑器实现原理</title>
           <meta charset="utf-8">
           <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
           <style>
                #edit{
                        height:260px;
                        width:100%;
                        overflow: scroll; 
                        border:solid 1px black
                }
           </style>
       </head>
       <body>
           <div id="edit" name="edit" contenteditable="true"></div>
               <br>
           <button name="button-edit" data-name="justifyCenter">居中</button>
           <button name="button-edit"  data-name="justifyLeft">左对齐</button>
           <button name="button-edit"  data-name="justifyRight">右对齐</button>
           <button name="button-edit"  data-name="forecolor" data-value="red">红色字体</button>
           <button name="button-edit"  data-name="backColor" data-value="lightgreen">浅绿背景</button>
           <button name="button-edit"  data-name="bold">加粗</button>
           <button name="button-edit"  data-name="italic">斜体</button>    
           <button name="button-edit"  data-name="underline">下划线</button> 

   
       <script>

            window.onload = function(){
                 edit.focus();
                 document.execCommand("formatblock", false, "p");
             }
            
           edit.onkeydown = function(){
                   var str = edit.innerHTML;
                   var val = str.search(/<\/li>/i);
                   if(val < 0){
                         document.execCommand("formatblock", false, "p");
                   }
             }
         
           var btns = document.getElementsByName('button-edit');
            
           for(var i = 0; i < btns.length; i++){
               btns[i].onclick = function(){
                       if(this.getAttribute('data-value') == ""){
                           document.execCommand(this.getAttribute('data-name'));
                       }else{
                           document.execCommand(this.getAttribute('data-name'),false,this.getAttribute('data-value'));
                       }
                   }
               }
   
             function showContent() {
                   alert(edit.innerHTML);
               }
               
            function isPaste(){
                     if(document.execCommand("paste")) {
                                 alert("浏览器支持或开启了paste粘贴命令！");
                       }else{
                                 alert("浏览器不支持paste粘贴命令，\n或未在user.js配置文件中开启！");
                       }
               }
           </script>
       </body>
   </html>